"""
SqlAlchermy ORM关系 - 一对多
"""

import os
import sys

path = os.path.dirname(__file__)
sys.path.append(os.path.join(path, '..'))

from faker import Faker
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref
from conf.mysql_config import SESSION, BASE


class User(BASE):
    __tablename__ = 'user'
    id = Column(Integer, autoincrement=True, primary_key=True)
    name = Column(String(10), comment='姓名', doc={'zh': '姓名'})

    # address_list = relationship('UserAddress')

    def __str__(self):
        return f'<User name={self.name}>'

    __repr__ = __str__


class UserAddress(BASE):
    __tablename__ = 'user_address'
    id = Column(Integer, autoincrement=True, primary_key=True)
    address = Column(String(250), comment='地址', doc={'zh': '地址'})
    user_id = Column(Integer, ForeignKey('user.id'))
    # 在ORM层面绑定两者之间的关系，第一个参数是绑定的表的类名
    # 第二个参数backref是通过User反向访问时的字段名称
    # user = relationship('User', backref="address_list")
    # TODO 配合demo13测试懒加载
    user = relationship('User', backref=backref('address_list', uselist=True, lazy='dynamic'))

    def __str__(self):
        return f'<UserAddress name={self.address}>'

    __repr__ = __str__


BASE.metadata.create_all()
fake = Faker(locale='zh_CN')


def add_data():
    user = User(name=fake.name())
    user.address_list = [UserAddress(address=fake.address()) for _ in range(5)]
    SESSION.add(user)
    SESSION.commit()


def search_data():
    address = SESSION.query(UserAddress).first()
    print(address)
    print(address.user)
    user = SESSION.query(User).first()
    print(user)
    print(user.address_list)


if __name__ == '__main__':
    search_data()
